package com.happy.study.servier.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.happy.study.dao.DataMapper;
import com.happy.study.entity.DataEntity;
import com.happy.study.servier.IDataService;
import com.happy.study.util.StateEnum;
import com.happy.study.util.StateException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class DataServiceImpl extends ServiceImpl<DataMapper, DataEntity> implements IDataService {

    @Resource
    private DataMapper dataMapper;

    @Override
    public List<DataEntity> queryList ( DataEntity dataEntity ) {
        if ( dataEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        List<DataEntity> dataEntities = dataMapper.queryList ( dataEntity.getCategoryId (), ( dataEntity.getPageNum () - 1 ) * dataEntity.getPageSize (), dataEntity.getPageSize () );
        return dataEntities;
    }

    @Override
    public Integer queryCount ( DataEntity dataEntity ) {
        if ( dataEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        Integer integer = dataMapper.queryCount ( dataEntity.getCategoryId () );
        return integer;
    }

    @Override
    public DataEntity querySingle ( DataEntity dataEntity ) {
        if ( dataEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        DataEntity data = baseMapper.selectOne ( new QueryWrapper<DataEntity> ().eq ( "id", dataEntity.getId () ) );
        return data;
    }

    @Override
    public DataEntity saveSingle ( DataEntity dataEntity ) {
        if ( dataEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        dataEntity.setCreateTime ( new Date () );
        int insert = baseMapper.insert ( dataEntity );
        if ( insert == 0 ) {
            throw new StateException ( StateEnum.INSERT_EXCE );
        }
        return dataEntity;
    }

    @Override
    public DataEntity updateSingle ( DataEntity dataEntity ) {
        if ( dataEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        dataEntity.setChangeTime ( new Date () );
        int count = baseMapper.updateById ( dataEntity );
        if ( count == 0 ) {
            throw new StateException ( StateEnum.UPDATE_EXCE );
        }
        return dataEntity;
    }
}
